package by.bsu.scs_bsu.custom_tags;

import javax.servlet.ServletException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.apache.log4j.Logger;

public class InsertTag extends SimpleTagSupport {

	private static final Logger LOGGER = Logger.getLogger("system_logger");
	
	private String definitionName;
	private String parameterName;
	
	public void setDefinition(String definitionName) {
		this.definitionName = definitionName;
	}
	
	public void setParameter(String parameterName) {
		this.parameterName = parameterName;
	}
	
	public void doTag() throws JspTagException {
		Definition definition = null;
		Parameter parameter = null;
		PageContext context = (PageContext) getJspContext();
		boolean isDirectInclude = false;
		
		definition = (Definition) context.getAttribute(definitionName, context.APPLICATION_SCOPE);
		
		if( (parameterName != null) && (definition != null) ) {
			parameter = definition.getParameter(parameterName);
		}
		
		if( parameter != null) {
			isDirectInclude = parameter.isDirect();
		}
		
		try {
			if( isDirectInclude && parameter != null ) {
				context.getOut().print(parameter.getValue());
			}
			else {
				if( parameter != null && parameter.getValue() != null) {
					context.include(parameter.getValue());
				}
			}
			
		} catch (Exception ex) {
	        Throwable rootCause = null;
	
	        if (ex instanceof ServletException) {
	            rootCause = ((ServletException) ex).getRootCause();
	        }
	        
	        throw new JspTagException(
	            ex.getMessage(),
	            rootCause);
	    }
	}
}
